package cn.edu.sdjzu.xg.bysj.controller.basic;

import cn.edu.sdjzu.xg.bysj.domain.OpenArea;
import cn.edu.sdjzu.xg.bysj.service.OpenAreaService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import util.Condition;
import util.ControllerHelper;
import util.JSONUtil;
import util.Pagination;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Slf4j
@WebServlet("/OpenArea1.ctl")
public class OpenAreaController extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();

        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //将request body转换为JSON字串
        String req_jsonStr = JSONUtil.getJSON(request);
        //将request body解析为JSONObject对象
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        //如果请求body为空
        if (req_jsonObj == null) {
            respMessage_jsonObj.put("message","未收到请求信息！");
            response.getWriter().println(respMessage_jsonObj);
            return;
        }
        Object id_obj = req_jsonObj.get("id");
        Object teacherId_obj = req_jsonObj.get("teacherId");
        Object graduateProjectCategoryId_obj = req_jsonObj.get("graduateProjectCategoryId");

        try {
            if (id_obj != null){
                int id_int = Integer.parseInt(id_obj.toString());
                responseOpenArea(id_int, response);
            } else {
                //请求中包含条件和分页信息，需要响应多个教师对象

                //读取分页信息，形成分页对象
                //从JSONObject对象中读取 “pagination” 键对应的值(JSONObject对象)
                Pagination pagination = ControllerHelper.getPagination(req_jsonObj);
                //从请求JSONObject对象中读取键“conditionList”对应的值(描述查询条件的JSONArray对象)
                if (teacherId_obj != null){
                    Integer teacherId = Integer.parseInt(teacherId_obj.toString());
                    Condition condition_teacherId = new Condition(
                            "teacher_id", " = ", teacherId.toString());

                    List<Condition> conditions = new ArrayList<Condition>();

                    conditions.add(condition_teacherId);
                    this.responseOpenAreas(response,conditions,pagination);
                } else if(graduateProjectCategoryId_obj != null){
                    Integer graduateProjectCategoryId = Integer.parseInt(graduateProjectCategoryId_obj.toString());

                    Condition condition_graduateProjectCategoryId =
                            new Condition("graduateProjectCategory_id",
                                    " = ",
                                    graduateProjectCategoryId.toString());

                    List<Condition> conditions = new ArrayList<Condition>();
                    conditions.add(condition_graduateProjectCategoryId);
                    this.responseOpenAreas(response,conditions,pagination);

                }else {
                    List<Condition> conditionList = ControllerHelper.getConditions(req_jsonObj);
                    //响应多个教师信息，其中conditionList, pagination两个对象引用为空是可能的
                    this.responseOpenAreas(response, conditionList, pagination);
                }

            }

        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试（要用log4j代替）
            log.debug(e.getMessage(),e);
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //响应respMessage_jsonObj到前端
            response.getWriter().println(respMessage_jsonObj);
            //打印异常栈，方便调试（要用log4j代替）
            log.debug(e.getMessage(),e);
        }
    }
    //响应一个系对象
    private void responseOpenArea(int id, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        //根据id查找系
        OpenArea openArea = OpenAreaService.getInstance().find(id);
        String openArea_json = JSON.toJSONString(openArea);

        //响应school_json到前端
        response.getWriter().println(openArea_json);
    }
    //响应所有系对象
    private void responseOpenAreas(HttpServletResponse response,
                                   List conditions_json, Pagination pagination)
            throws ServletException, IOException, SQLException {
        //获得所有系
        Collection<OpenArea> openAreas = OpenAreaService.getInstance()
                .findAll(conditions_json,pagination);
        String openAreas_json = JSON.toJSONString(openAreas,
                SerializerFeature.DisableCircularReferenceDetect);

        JSONObject message = new JSONObject();
        message.put("totalNum",pagination.getTotalNum());
        message.put("data",openAreas);
        //响应schools_json到前端
        response.getWriter().println(openAreas_json);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置请求字符编码为UTF-8
        request.setCharacterEncoding("UTF-8");
        //根据request对象，获得代表新增Teacher的JSON字串
        String req_openAreaToAdd_jsonStr = JSONUtil.getJSON(request);
        //将JSON字串解析为Teacher对象
        OpenArea openAreaToAdd = JSON.parseObject(
                req_openAreaToAdd_jsonStr, OpenArea.class);

        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            //在数据库表中增加Teacher对象
            OpenAreaService.getInstance().add(openAreaToAdd);
            respMessage_jsonObj.put("message", "增加成功");
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            //打印异常栈，方便调试（要用log4j代替）
            log.debug(e.getMessage());
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //打印异常栈，方便调试（要用log4j代替）
            log.debug(e.getMessage());
        }
        //响应respMessage_jsonObj到前端
        response.getWriter().println(respMessage_jsonObj);
    }

    @Override
    protected void doDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //将request参数转换为JSON字串
        String request_json_str = JSONUtil.getJSON(request);
        //将请求body解析为要删除的Teacher的id对应的JSONObject对象(可能是{"id":1})
        JSONObject idOfOpenAreaToDelete_jsonObj = JSON.parseObject(request_json_str);

        //从JSONObject对象中读取键“id”的值（Java Object对象），
        Object id_obj = idOfOpenAreaToDelete_jsonObj.get("id");
        int id_int = Integer.parseInt(id_obj.toString());

        //用于调试，要使用log4j代替
        log.debug("id=" + id_int);
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            //到数据库表中删除对应的教师
            OpenAreaService.getInstance().delete(id_int);
            respMessage_jsonObj.put("message", "删除成功");
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            //打印异常栈，方便调试（要用log4j代替）
            log.debug(e.getMessage());
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //打印异常栈，方便调试（要用log4j代替）
            log.debug(e.getMessage());
        }
        //响应respMessage_jsonObj到前端
        response.getWriter().println(respMessage_jsonObj);
    }
    @Override
    protected void doPut(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //设置请求字符编码为UTF-8
        request.setCharacterEncoding("UTF-8");
        String openAreaToUpdate_jsonStr = JSONUtil.getJSON(request);
        //将JSON字串解析为要修改的Teacher对象（有id的完整对象）
        OpenArea openAreaToUpdate = JSON.parseObject(openAreaToUpdate_jsonStr, OpenArea.class);
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        try {
            //到数据库表修改Teacher对象对应的记录
            OpenAreaService.getInstance().update(openAreaToUpdate);
            respMessage_jsonObj.put("message", "修改成功");
        } catch (SQLException e) {
            respMessage_jsonObj.put("message", "数据库操作异常");
            //打印异常栈，方便调试（要用log4j代替）
            log.debug(e.getMessage());
        } catch (Exception e) {
            respMessage_jsonObj.put("message", "网络异常");
            //打印异常栈，方便调试（要用log4j代替）
            log.debug(e.getMessage());
        }
        //响应respMessage_jsonObj到前端
        response.getWriter().println(respMessage_jsonObj);
    }
}
